package cn.com.jinhao.provider.business.service.impl;

import cn.com.jinhao.hotline.commons.base.constant.SystemConstant;
import cn.com.jinhao.hotline.commons.exception.BusinessErrorException;
import cn.com.jinhao.hotline.commons.util.ExeclUtil;
import cn.com.jinhao.hotline.commons.vo.business.RecordInfoRequestVO;
import cn.com.jinhao.hotline.commons.vo.business.finished.FinishedCondition;
import cn.com.jinhao.hotline.commons.vo.business.finished.FinishedRequestVO;
import cn.com.jinhao.provider.business.entity.WorkFinished;
import cn.com.jinhao.provider.business.mapper.SysDictMapper;
import cn.com.jinhao.provider.business.mapper.WorkFinishedMapper;
import cn.com.jinhao.provider.business.service.RecordInfoService;
import cn.com.jinhao.provider.business.service.SysDictService;
import cn.com.jinhao.provider.business.service.WorkFinishedService;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * hotline-spring-cloud
 * <p>Description: </p>
 *
 * @author ShaneMew
 * @version 1.0
 * @date 2020/6/3
 * @since 2020/6/3
 */
@Service
public class WorkFinishedServiceImpl extends CommonService implements WorkFinishedService {
    @Resource
    WorkFinishedMapper workFinishedMapper;

    @Resource
    RecordInfoService recordInfoService;

    @Resource
    SysDictService sysDictService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(FinishedRequestVO finishedRequestVO) throws Exception {
        WorkFinished workFinished = new WorkFinished();
        BeanUtil.copyProperties(finishedRequestVO, workFinished);
        // 获得code
        String code = super.getCode(SystemConstant.CodeType.COMPLEX);
        // 生成快照
        String dataSnap = this.getDetailMsg(workFinished.getDept(), workFinished.getOperator(), workFinished.getEventCode());

        workFinished.setCode(code);
        workFinished.setDataSnap(dataSnap);
        workFinished.setVersion(1);
        int result = workFinishedMapper.insertSelective(workFinished);
        if (result == 0) {
            throw new BusinessErrorException("新增办结信息失败");
        }

        //TODO: 判断办结时是否自动撤单开启,如果开启所有其它未反馈的工单立即撤单并无需审核
        String isAutoCancel = Optional.ofNullable(
            sysDictService.queryByCodeAndPaid(SystemConstant.SysDict.EVENT_FINISHED_SETTING.getCode(), SystemConstant.SysDict.EVENT_FINISHED_SETTING.getName()).getSysValue()).orElseThrow(() -> new BusinessErrorException("系统配置项找不到，请检查是否存在（是否开启办结撤回没反馈工单）的选项"));

        if (Boolean.parseBoolean(isAutoCancel)) {
            //TODO: 进行撤单无需审核
        }
        RecordInfoRequestVO recordInfo = new RecordInfoRequestVO();
        recordInfo.setCode(workFinished.getEventCode());
        // 事件表的是否办结更新为已办结
        recordInfo.setIsFinish((short)1);
        // 事件状态更新为待回访
        recordInfo.setEventStatusCode(SystemConstant.FlowStatus.VISIT.getStatusCode());
        recordInfo.setEventStatus(SystemConstant.FlowStatus.VISIT.getStatus());
        recordInfoService.update(recordInfo);
        // 跟新任务流程状态
    }

    @Override
    public void update(FinishedRequestVO finishedRequestVO) throws Exception {
        WorkFinished workFinished = new WorkFinished();
        BeanUtil.copyProperties(finishedRequestVO, workFinished);

        Example example = new Example(WorkFinished.class);
        example.createCriteria().andEqualTo("code", workFinished.getCode()).andEqualTo("version", workFinished.getVersion());
        workFinished.setVersion(workFinished.getVersion() + 1);
        int result = workFinishedMapper.updateByExample(workFinished, example);
        if (result == 0) {
            throw new BusinessErrorException("更新办结信息失败");
        }
    }

    @Override
    public void delete(String id) throws Exception {
        int result = workFinishedMapper.deleteByPrimaryKey(id);
        if (result == 0) {
            throw new BusinessErrorException("删除办结信息失败");
        }
    }

    @Override
    public Map<String, Object> selectByCondition(FinishedCondition conditions) {
        HashMap<String, Object> map = new HashMap<>(10);
        Example example =  getExample(conditions);
        if (conditions.getIsExport()) {
            List<WorkFinished> workFinishedList = workFinishedMapper.selectByExample(example);
            List<String> headers = conditions.getHeaders();
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(workFinishedList));
            String fileInfo = new ExeclUtil().exportExecl(headers,jsonArray,"F:\\");
            map.put("fileInfo", fileInfo);
        }else {
            if (conditions.getPageNo() != 0 && conditions.getPageSize() != 0) {
                PageHelper.startPage(conditions.getPageNo(), conditions.getPageSize());
                PageInfo<WorkFinished> pageInfo = new PageInfo<>(workFinishedMapper.selectByExample(example));
                map.put("list", pageInfo);
                map.put("total", pageInfo.getTotal());
                map.put("pageSize", pageInfo.getPageSize());
                map.put("pageNo", pageInfo.getPageNum());
            } else {
                List<WorkFinished> workFinisheds = workFinishedMapper.selectByExample(example);
                map.put("list", workFinisheds);
                map.put("total", workFinisheds.size());
            }
        }
        return map;
    }

    @Override
    public WorkFinished detailByEventCodeAndDispatchCode(String eventCode, String workOrderCode) throws Exception {
        Example example = new Example(WorkFinished.class);
        example.createCriteria().andEqualTo("eventCode", eventCode).andEqualTo("workOrderCode", workOrderCode);

        return Optional.ofNullable(workFinishedMapper.selectOneByExample(example)).orElseThrow(() -> new BusinessErrorException("查询不到办结信息"));
    }

    @Override
    public WorkFinished detailByCode(String code) throws Exception {
        Example example = new Example(WorkFinished.class);
        example.createCriteria().andEqualTo("code", code);
        return Optional.ofNullable(workFinishedMapper.selectOneByExample(example)).orElseThrow(() -> new BusinessErrorException("查询不到办结信息"));
    }

    String getDetailMsg(String dept, String oper, String eventCode) {
        LocalDateTime todayDate = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return "【" +
            dept +
            "】的【" +
            oper +
            "】于【" +
            dtf.format(todayDate) +
            "】办结了事件：【" +
            eventCode +
            "】";
    }

     Example getExample(FinishedCondition conditions) {
        Example example = new Example(WorkFinished.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(conditions.getEventCode())) {
            criteria.andEqualTo("eventCode", conditions.getEventCode());
        }

        if (StringUtils.isNotBlank(conditions.getDispatchCode())) {
            criteria.andEqualTo("dispatchCode", conditions.getDispatchCode());
        }
        example.orderBy("createTime").desc().orderBy("modifyTime").desc();
        return example;
    }
}
